package com.captain.leetcode.排序算法;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/3/20 17:44
 */
public class InsertionSort {
    public static void main(String[] args) {
        for (int i : new InsertionSort().insertionSort(new int[]{5, 4, 3, 2, 1}, 5)) {
            System.out.println(i);
        }


    }

    //插入排序
    public int[] insertionSort(int[] a, int n) {
        if (n <= 1) return a;
        //分为两部分
        for (int i = 1; i < n; i++) {
            int value = a[i];
            int j = i - 1;

            for (; j >= 0; j--) {
                if (a[j] > value) {
                    a[j + 1] = a[j];
                } else {
                    break;
                }
            }
            a[j + 1] = value;
        }
        return a;
    }
}
